import nedb from './nedb'
import http from 'axios'
import store from '../store'
// 详细用户列表
export default {
  /**
   * 获取用户列表
   * @param {int} csId 客服ID
   */
  async getUserList (csId) {
    try {
      var _cslist
      // 1.用csId来查询是否是组长，是的话 返回所有的下级客服
      var config = {
        params: {cs_id: csId}
      }
      var csType = await http.get(store.state.Config.base_url + '/csuser/leaders', config)
      csType = csType.data
      if (csType.code === 2) {
        _cslist = [csId]
      } else if (csType.code === 1) {
        _cslist = [csId] = csType.data
      }
      // 2.用得到的csid列表来查询数据库
      var result = await nedb.sql_user.find({
        butt_id: {$in: _cslist}
      })
      if (result.length > 0) {
        return Promise.resolve(result)
      }
      return Promise.resolve([])
    } catch (e) {
      return Promise.resolve([])
    }
  },
  /**
   * 获取单个用户
   * @param {String} csId 用户的OPENID
   */
  async getUser (openid) {
    try {
      var result = await nedb.sql_user.find({
        openid: openid
      })
      if (result.length > 0) {
        return Promise.resolve(result[0])
      }
      return Promise.resolve(null)
    } catch (e) {
      return Promise.resolve(null)
    }
  },
  async addUser (user) {
    try {
      // 1.先用opid在数据库查找，有就替换
      var oldResult = await nedb.sql_user.find({
        openid: user.openid
      })
      if (oldResult.length > 0) {
        await nedb.sql_user.update({openid: user.openid}, user)
      } else {
        await nedb.sql_user.insert(user)
      }
      return Promise.resolve(user)
    } catch (e) {
      return Promise.resolve(null)
    }
  }
}
